﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace ReLifeProject.Controllers.Post
{
    [ApiController]
    [AllowAnonymous]
    [Route("[controller]")]
    public class Post_fileUpload_vue_Controller : Controller
    {
        [HttpPost("/api/upload")]
        public async Task<IActionResult> Upload([FromServices] IWebHostEnvironment host)
        {
            var files = Request.Form.Files;
            long size = files.Sum(f => f.Length);
            List<string> list = new List<string>();
            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    var path = Path.Combine(host.WebRootPath == null ? host.ContentRootPath : host.WebRootPath, "files");

                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    string fileName = $"{Guid.NewGuid():N}{Path.GetExtension(formFile.FileName)}";
                    path = Path.Combine(path, fileName);
                    var filePath = path;

                    using var stream = System.IO.File.Create(filePath);
                    await formFile.CopyToAsync(stream);
                    var c = Path.VolumeSeparatorChar;
                    list.Add($"{Request.Scheme}://{Request.Host.Value}/{Path.Combine("files", fileName).Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)}");
                }
            }

            return Ok(new { list = list, size });
        }
    }
}
